package cn.ilikes.tools.hbase.jpa.clients;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.ilikes.tools.hbase.jpa.JPAHbasePersistenUnitEnv;
import cn.ilikes.tools.hbase.jpa.SysConfigs.DataStoreType;
import cn.ilikes.tools.hbase.jpa.clients.datahander.DataHander;
import cn.ilikes.tools.hbase.jpa.clients.datahander.HbaseDataHander;
import cn.ilikes.tools.hbase.jpa.clients.datasource.DataSource;
import cn.ilikes.tools.hbase.jpa.clients.datasource.HbaseDataSource;
import cn.ilikes.tools.hbase.jpa.indexs.IndexClient;
import cn.ilikes.tools.hbase.jpa.metadatas.sub.configs.Datastorefactory.DataStore;

//implements ClientFactory
public class ClientFactoryImple {

	/**
	 * key :PersistenceUnitsName
	 */
	private static Map<String, DataSource> hbaseDataSourceMap = new ConcurrentHashMap<String, DataSource>();

	public static AbClient createClient(DataStore dataStore, IndexClient indexClient, JPAHbasePersistenUnitEnv hbasePersistenUnitEnv) {

		DataStoreType dataStoreType = dataStore.getDataStoreType();

		switch (dataStoreType) {
		case hbase: {
			DataSource dataSource = hbaseDataSourceMap.get(hbasePersistenUnitEnv.getPersistenceUnitsName());
			if (dataSource == null) {
				synchronized (hbaseDataSourceMap) {
					dataSource = new HbaseDataSource(dataStore);
					hbaseDataSourceMap.put(hbasePersistenUnitEnv.getPersistenceUnitsName(), dataSource);
				}
			}

			DataHander dataHander = new HbaseDataHander((HbaseDataSource) dataSource, hbasePersistenUnitEnv);
			AbClient client = new HbaseClient(indexClient, dataHander, hbasePersistenUnitEnv);
			return client;
		}
		default:
			throw new JPAHBaseClientsRuntimeException("this " + dataStoreType + "'s DataStore not find ! ");
		}
	}

}
